<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>localStorage的使用</title>
  </head>

  <body>
    <h1>localStorage的使用</h1>
    <button class="btn01">保存数据</button>
    <button class="btn02">读取数据</button>
    <button class="btn03">删除数据</button>
    <button class="btn04">清空数据</button>
  </body>
  <script>
    /* 
    1.localStorage里面存的是字符串，如果需要存数组和对象的话，用JSON.stringify()转化
    */
    let btn01 = document.querySelector(".btn01");
    let btn02 = document.querySelector(".btn02");
    let btn03 = document.querySelector(".btn03");
    let btn04 = document.querySelector(".btn04");

    const arr = [10, 20, 30, 40];
    const obj = {
      id: 1000,
      name: "grace",
      age: 20,
      show: function () {
        console.log("我长得好看");
      }
    }
    //1.设置数据
    btn01.onclick = function () {
      localStorage.setItem("name", "jason");
      // 存储的不是字符串，数组，对象最好使用JSON.stringify()转换成JSON字符串
      localStorage.setItem("obj", JSON.stringify(obj));
      localStorage.setItem("arr", JSON.stringify(arr));
    }
    // 2.读取数据
    btn02.onclick = function () {
      let p = localStorage.getItem("name");
      let o = localStorage.getItem("obj");
      let arr = localStorage.getItem("arr");

      try {
        //尝试着解析，一旦解析失败，移除该数据
        console.log(p); //字符串不要使用JSON解析
        console.log(JSON.parse(o));
        console.log(JSON.parse(arr));
      } catch (error) {
        console.log(error.message);
        // 移除localStorage
        localStorage.removeItem("arr")
        localStorage.removeItem("name")
        localStorage.removeItem("obj")
      }

    }
    // 3.删除某个数据
    btn03.onclick = function () {
      localStorage.removeItem("arr")
    }

    // 4.清空所有数据
    btn04.onclick = function () {
      localStorage.clear()
    }
  </script>

</html>